package com.剑指offer.no37;

import java.util.*;


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}


public class Solution {

}


class Codec {
    public String serialize(TreeNode root) {
        if (root == null)
            return "[]";

        StringBuilder res = new StringBuilder("[");
        Queue<TreeNode> nodeQue = new LinkedList<>();

        nodeQue.offer(root);

        while (!nodeQue.isEmpty()) {
            TreeNode node = nodeQue.poll();
            if (node != null) {
                res.append(node.val + ",");
                nodeQue.add(node.left);
                nodeQue.add(node.right);
            } else res.append("null,");
        }

        // 记得删掉最后一个逗号！
        res.deleteCharAt(res.length() - 1);

        res.append("]");

        return res.toString();
    }

    public TreeNode deserialize(String data) {
        if (data.equals("[]"))
            return null;

        // 去掉首部和尾部的[]字符，并分割成string列表
        String[] vals = data.substring(1, data.length() - 1).split(",");

        TreeNode root = new TreeNode(Integer.parseInt(vals[0]));

        Queue<TreeNode> nodeQue = new LinkedList<>();

        nodeQue.offer(root);

        // 结点指针索引
        int i = 1;
        while (!nodeQue.isEmpty()) {

            TreeNode node = nodeQue.poll();

            // 接左节点
            if (!vals[i].equals("null")) {
                node.left = new TreeNode(Integer.parseInt(vals[i]));
                nodeQue.add(node.left);
            }else {
                node.left = null;
            }

            i++;

            // 接右结点
            if (!vals[i].equals("null")) {
                node.right = new TreeNode(Integer.parseInt(vals[i]));
                nodeQue.add(node.right);
            }else {
                node.right = null;
            }

            i++;
        }
        return root;
    }
}
